﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

using Happy.ExtentionMethods;

namespace Happy.Domain.EntityFramework
{
    /// <inheritdoc />
    public class UnitOfWork : DbContext, IUnitOfWork
    {
        private readonly List<IInterceptor> _interceptors = new List<IInterceptor>();

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected UnitOfWork() { }

        /// <summary>
        /// 构造方法。
        /// </summary>
        protected UnitOfWork(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        /// <inheritdoc />
        public void Flush()
        {
            try
            {
                foreach (var interceptor in _interceptors)
                {
                    interceptor.BeforeFlush(this);
                }

                base.SaveChanges();

                foreach (var interceptor in _interceptors)
                {
                    interceptor.AfterFlush(this);
                }
            }
            catch (DbUpdateConcurrencyException ex)
            {
                throw new OptimisticConcurrencyException(ex);
            }
        }

        /// <inheritdoc />
        public void Clear()
        {
            base.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = EntityState.Detached);
        }

        /// <summary>
        /// 注册拦截器。
        /// </summary>
        public UnitOfWork RegisterInterceptor(IInterceptor interceptor)
        {
            interceptor.MustNotNull("interceptor");

            _interceptors.Add(interceptor);

            return this;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Configurations.AddFromAssembly(this.GetType().Assembly);
        }
    }
}
